<?php
declare (strict_types=1);

namespace app\common\model;

use ffhome\frame\model\BaseModel;
use think\facade\Db;

class TallyProgressDay extends BaseModel
{
    const MODEL_NAME = 'tally_progress_day';
    /**
     * 日报
     */
    const T_REPORT = 1;
    /**
     * 小结
     */
    const T_SUMMARY = 2;
    /**
     * 未完成
     */
    const CS_UNDO = 1;
    /**
     * 部分完成
     */
    const CS_HALF = 2;
    /**
     * 全部完成
     */
    const CS_OK = 3;
    /**
     * 需协助
     */
    const CS_HELP = 4;

    public static function generateTomorrowPlan()
    {
        return self::generateEmpty(self::T_REPORT, currentUserId(),
            date('Y-m-d', strtotime(date('Y-m-d') . ' +1 day')));
    }

    private static function generateEmpty($type, $accountingId, $date)
    {
        $data = ['accounting_id' => $accountingId, 'progress_date' => $date, 'type' => $type,];
        $day = Db::name(self::MODEL_NAME)->field('id')->where($data)->find();
        if (!empty($day)) {
            return $day['id'];
        }
        if ($type == self::T_SUMMARY) {
            $data['completion_status'] = $data['appraise'] = 0;
        }
        $data['create_by'] = $data['update_by'] = $data['accounting_id'];
        $data['create_time'] = $data['update_time'] = date('Y-m-d H:i:s');
        return Db::name(self::MODEL_NAME)->insertGetId($data);
    }

    public static function get($dayId)
    {
        return Db::name(self::MODEL_NAME)->find($dayId);
    }

    public static function generateEmptySummary()
    {
        $days = (12 - date('N')) % 7;//统一获取下一个星期五
        return self::generateEmpty(self::T_SUMMARY, currentUserId(),
            date('Y-m-d', strtotime(date('Y-m-d') . " +{$days} day")));
    }

    public static function countByAccountingIdAndDate($accountingId, $progressDate)
    {
        return Db::name(self::MODEL_NAME)
            ->where(['accounting_id' => $accountingId, 'progress_date' => $progressDate, 'type' => self::T_REPORT])
            ->count();
    }

    public static function updateCompletionStatus($id)
    {
        Db::name(self::MODEL_NAME)->update(['id' => $id, 'completion_status' => self::computeCompletionStatus($id)]);
    }

    private static function computeCompletionStatus($id)
    {
        $list = TallyTodo::getListByDayId($id);
        $status = count($list) == 0 ? self::CS_UNDO : $list[0]['completion_status'];
        foreach ($list as $vo) {
            if ($vo['completion_status'] == self::CS_HELP) {
                return self::CS_HELP;
            }
            if ($status != $vo['completion_status']) {
                return self::CS_HALF;
            }
        }
        return $status;
    }
}